package com.fare.taluo.message;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.Logger;

/**
 * 消息处理机制配置文件
 * <p>负责将message.properties配置文件读取到单实例的配置类中，以供消息处理类{@link SendEmail}或{@link SendSMS}调用
 * <p>单实例的配置类包括{@link MessageEmailProperties}邮件配置,{@link MessageSMSProperties}短信配置
 * <p>有一个重载的方法reload(),可以在修改配置后，手动重载
 * @author xiangsf 2012-12-8
 *
 */
public class MessageConfiguration {

	protected Logger logger = Logger.getLogger(getClass());
	
	public final static String SYSTEM_IDENTITY = "message.system.identity";
	
	public final static String config_file = "message.properties";
	
	private static MessageConfiguration _instance = new MessageConfiguration();
	
	
	private EmailMessageProperties emailProperties;
	private SMSMessageProperties smsProperties;
	private String systemIdentity; //系统标识符
	private boolean hasLoaded = false;
	private MessageConfiguration(){
		emailProperties = new EmailMessageProperties();
		smsProperties = new SMSMessageProperties();
		try {
			load();
		} catch (ConfigurationException e) {
			logger.error("消息处理配置文件初始化加载失败!系统自动将没有启用置为未启用!",e);
			emailProperties.setEmailServerSwitch(false);
			smsProperties.setSmsServerSwitch(false);
		}
	}
	public static MessageConfiguration getInstance(){
		if(_instance == null)
			_instance = new MessageConfiguration();
		return _instance;
	}
	/**
	 * 读取配置文件，设置值
	 * @throws ConfigurationException
	 */
	public void load() throws ConfigurationException{
		if(!hasLoaded){
			PropertiesConfiguration pc= new PropertiesConfiguration(config_file);
			this.systemIdentity = pc.getString(SYSTEM_IDENTITY);
			emailProperties.setProperties(pc);
			smsProperties.setProperties(pc);
			hasLoaded = true;
		}
	}
	/**
	 * 重新读取配置文件，设置值
	 * @throws ConfigurationException
	 */
	public void reload() throws ConfigurationException{
		destroy();
		load();
	}
	public void destroy(){
		emailProperties = null;
		smsProperties = null;
		hasLoaded = false;
	}
	
	public EmailMessageProperties getEmailProperties() {
		return emailProperties;
	}
	
	public SMSMessageProperties getSmsProperties() {
		return smsProperties;
	}
	public String getSystemIdentity() {
		return systemIdentity;
	}
	public void setSystemIdentity(String systemIdentity) {
		this.systemIdentity = systemIdentity;
	}
	
	
}
